﻿// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <memory>
#include <cassert>

#pragma pack(push,1)

const int HTTP_METHOD_GET = 0;
const int HTTP_METHOD_POST = 1;
const int HTTP_METHOD_PUT = 2;

struct THTTPHeader {
	const char* name;
	const char* value;
};

struct THTTPResponse 
{
	int status_code;
	long long user_data;
	const char* error_msg;
	const char* data;
	int size;
};

struct THTTPRequest
{
	const char* url;
	int method;
	THTTPHeader headers[128];
	const char* data;
	int size;
	long long user_data;
	void(*callback)(THTTPResponse*);
	unsigned long long connect_timeout;
	unsigned long long timeout;

};

void request_append_header(THTTPRequest* req, const char* name, const char* value) {
	for (uint32_t i = 0; i < sizeof(req->headers )/ sizeof(req->headers[0]); ++i) 
	{
		if (req->headers[i].name == nullptr)
		{
			req->headers[i].name = name;
			req->headers[i].value = value;
			return;
		}
	}
	assert(false && "header full!");
}

struct THTTPServerRequest {
	const char* url;
	void* resp_sender;
	const char* method;
	const void* data;
	int size;
	unsigned long long user_data;
	THTTPHeader headers[128];
};

struct THTTPServerResponse {
	void* sender;
	int status;
	const char* data;
	int size;
	THTTPHeader headers[128];
};

struct THTTPServerOptions {
	unsigned long long user_data;
	void(*handler)(THTTPServerRequest*);
	const char* addr;
};

#pragma pack(pop)

#include <string>

extern "C" void http_request(const THTTPRequest* req);
extern "C" void http_server_start(THTTPServerOptions* options);
extern "C" bool http_server_free(void* serverInfo);
extern "C" void http_server_response(THTTPServerResponse* res);

void onCallback(THTTPResponse* res) {
	std::cout << "onCallback " 
		<< " status=" << res->status_code
		<< std::string(res->data,res->size) << " len=" << res->size 
		<< "error=" << (res->error_msg != nullptr ? res->error_msg : "")
		<< " userdata=" << res->user_data
		<<  std::endl;

}

#include <chrono>
#include <thread>

void http_callback(THTTPServerRequest* req) {
	THTTPServerResponse res = { 0 };
	res.status = 200;
	res.sender = req->resp_sender;
	res.data = "2343242342342";
	res.size = strlen(res.data);
	http_server_response(&res);
}

int main()
{
	THTTPServerOptions options = { 0 };
	options.addr = "127.0.0.1:8003";
	options.handler = &http_callback;
	http_server_start(&options);


	while (true) {
		std::this_thread::sleep_for(std::chrono::milliseconds(40));
	}
}

int main2()
{
	THTTPRequest r = { 0 };
	r.method = HTTP_METHOD_POST;
	r.data = "43253543534";
	r.size = (int)strlen(r.data);
	r.url = "https://baidu.com";
	r.callback = &onCallback;
	r.user_data = (long long)&r;
	request_append_header(&r, "content-type", "application/x-www-form-urlencoded; charset=UTF-8");
	http_request(&r);
	memset(&r, 0, sizeof(r));


	while (true) {
		std::this_thread::sleep_for(std::chrono::milliseconds(40));
	}
}
